package demo3;

/**
 * 二分查找
 */
public class binarySearchTest {
    public static void main(String[] args) {
        int[] arr = new int[]{2,5,7,8,12,15,18,20};
        System.out.println(binarySearch(arr,20));
    }

    public static int binarySearch(int[] arr,int target){
        if(arr.length == 0) return -1;
        int left = 0;
        int right = arr.length-1;
        int mid;
        while(left <= right){
            mid = (right - left)/2 + left;
            if(arr[mid] == target){
                return mid;
            }else{
                if(arr[mid] < target){
                    left = mid+1;
                }else{
                    right = mid-1;
                }
            }
        }
        return -1;
    }
}
